package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.controller.CheckInController;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.AgeCalculator;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-13
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInController checkInController;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn)?1:0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }
    /*
    入住申请
    * */

    @Override
    public void apply(CheckInApplyDto dto) {
        //判断老人是否已经入住
        //查询老人  通过身份证号查询
            //创建查询包装器elderQueryWrapper，用于设置查询条件。
           //设置两个查询条件：身份证号和状态值。
          //使用elderMapper查询符合条件的老人信息。
         //若查询结果不为空，则抛出异常“老人已入住”。
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<Elder>();
        elderQueryWrapper.eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo());
        elderQueryWrapper.eq(Elder::getStatus,1);
        Elder elder =  elderMapper.selectOne(elderQueryWrapper);
        if(ObjectUtils.isNotEmpty(elder)){
            throw new BaseException("老人已入住");
        }
      // 更新床位状态
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateBed(bed);

        //更新新增老人
            //调用新增老人方法
            elder = InsertOrUpDataElder(bed,dto.getCheckInElderDto());
        //新增签约办理信息 合同
            //调用新增签约办理方法
                //调用工具类生成合同编号
        String contractNumber = "HT" + CodeGenerator.generateContractNumber();
                //将数据装入数据对象中
        insertContract(elder,contractNumber,dto);
        //新增入住信息
        CheckIn checkIn = insertCheckInInfo(elder,bed,dto);
        //新增入住配置
        insertCheckInCongifg(checkIn,dto);
    }

    private void insertCheckInCongifg(CheckIn checkIn, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insertCheckInConfig(checkInConfig);
    }

    //新增入住信息
    private CheckIn insertCheckInInfo(Elder elder, Bed bed, CheckInApplyDto dto ) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStatus(0); //0是已入住  1是已退住
        checkIn.setBedNumber(bed.getBedNumber());
        //家属列表转换为json存在remark字段
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        checkInMapper.insertCheckIn(checkIn);
        return  checkIn;
    }

    private void insertContract(Elder elder, String contractNumber, CheckInApplyDto dto) {
        //属性拷贝
        CheckInContractDto checkInContractDto =dto.getCheckInContractDto();
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto,contract);
        //设置合同编号
        contract.setContractNumber(contractNumber);
        //设置老人id和名字
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        //设置创建时间和更新时间
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);

        Integer status = startDate.isAfter(LocalDateTime.now()) ? 1:0;
        contract.setStatus(status);
    }


    //新增或更新老人
    private Elder InsertOrUpDataElder(Bed bed, CheckInElderDto checkInElderDto) {
        //新建老人
        Elder elder = new Elder();
        //拷贝和补充数据
        BeanUtils.copyProperties(checkInElderDto ,elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        //将老人状态设置为1
        elder.setStatus(1);
        elder.setCreateTime(new Date());
        //判断是该在数据库中保存还是更新
        LambdaQueryWrapper <Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        elderQueryWrapper.eq(Elder::getIdCardNo,elder.getIdCardNo());
        elderQueryWrapper.eq(Elder::getStatus,0);
        //elderDB从数据库查到的老人
        Elder elderDB = elderMapper.selectOne(elderQueryWrapper);
            if(ObjectUtils.isNotEmpty(elderDB)){
//                更新
                elder.setId(elderDB.getId());
                elderMapper.updateById(elder);
            }else {
                elderMapper.insertElder(elder);
            }
        return elder;
    }
    //新增签约办理信息

    //详细信息回显


    @Override
    public CheckInDetailVo getCheckInDetail(Long id) {
        //装最后返回的数据
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //根据ID查询入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //根据ID查询老人信息
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        //根据ID查询老人家属信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        //拷贝数据
        BeanUtils.copyProperties(elder,checkInElderVo);
        checkInElderVo.setAge(AgeCalculator.getAgeByIdCard(elder.getIdCardNo()));
        //装入数据
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        //查询入住配置信息
        LambdaQueryWrapper<CheckInConfig> checkInConfigQueryWrapper = new LambdaQueryWrapper<>();
        checkInConfigQueryWrapper.eq(CheckInConfig::getCheckInId,checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigQueryWrapper);
        //属性拷贝
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        //补全数据
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        //封装数据
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        //合同信息
          //查询合同信息
        LambdaQueryWrapper<Contract> contractQueryWrapper = new LambdaQueryWrapper<>();
        contractQueryWrapper.eq(Contract::getElderId,elder.getId());
        Contract contract = contractMapper.selectOne(contractQueryWrapper);
        checkInDetailVo.setContract(contract);
        //处理家属列表的数据
        String familyListStr = checkIn.getRemark();
        //将json数据转成list并存入
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(familyListStr, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);

        return  checkInDetailVo;
    }
}
